<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="/css/jsdeliverbootstrap.min.css">
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--          integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
    <link rel="stylesheet" href="/css/pet-store-plus.css">

    <link rel="stylesheet" href="/css/staticfilebootstrap.min.css">
<!--    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->
    <script src="/js/chart.js"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->

    <title>Item管理</title>
</head>
<body>

<div th:replace="seller_commom"></div>

<div class="content" id="content">
        <div class="select">
            <select name="sortingorder" onchange="itemsort(this.value)">
                <option value="/admin/items" selected>默认排序</option>
                <option value="/admin/itemOrderBySales">按销量</option>
                <option value="/admin/itemOrderByPrice" >按价格</option>
            </select>
        </div>
<!--    </label>-->
    <div class="btn-group" role="group" aria-label="Basic example">
            <button type="button" class="btn btn-secondary" onclick="selectByStatus(this)" >全部状态</button>
            <button type="button" class="btn btn-secondary" onclick="selectByStatus(this)">已上架</button>
            <button type="button" class="btn btn-secondary" onclick="selectByStatus(this)">已下架</button>
    </div>
    <div class="searchgrp" >
        <form >
            <input type="text" placeholder="可通过商品名搜索..." class="searchinput" id="keyword" name="keyword">
            <button class="searchbtn" onclick="searchItem()" type="button"  >搜索</button>
<!--            ///admin/getItemListByKeyForJS-->
        </form>
    </div>
    <div style="grid-column: span 1"></div>
    <button class="Button" style="margin-top: 10px;width: 150px" onclick="window.location.href='/admin/add'" id="add">
        添加商品
    </button>
    <div class="tab-bg">
        <table class="item_tab"  id="item_tab" style="overflow: auto">
            <caption></caption>
            <thead>
            <tr>
                <th>产品名称</th>
                <th>价格</th>
                <th>Category</th>
                <th>Product</th>
                <th>库存</th>
                <th>销量</th>
                <th>是否上架</th>
                <th>描述</th>
                <th>浏览量</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="itemTabBody">
            <tr th:each="itemtab:${itemList}">

            </tr>
            </tbody>
        </table>
        <script th:inline="javascript">
            const tbody=document.getElementById('itemTabBody');
            let selectedStatus;

            window.addEventListener('load',function (){
                console.log('aaa');
                // var itemList = /*[[${itemList}]]*/ null;
                // console.log(itemList);
                var url='/admin/items';
                fetch(url,{
                    method:'GET',
                }).then(response=>{
                    if(!response.ok){
                        console.log("请求/admin/items失败，状态码：" + response.status);
                    }else {
                        return response.json();
                    }
                }).then(data=>{
                       updateTbody(data.data);
                })
            });

            // document.querySelector('#add').addEventListener('click', function() {
            //     window.location.href = this.getAttribute('href');
            // });

            // 假设 status 是产品状态，可以是 '已下架' 或 '上架'

            function onShelf(button) {
                var row = button.parentNode.parentNode;
                var itemId = row.querySelector('td:nth-child(1)').innerText;
                console.log(itemId);
                var isup=row.querySelector('td:nth-child(7)').innerText.trim() === '是' ? '1' : '0';
                console.log(row.querySelector('td:nth-child(7)').innerText);
                console.log('isup= '+isup);
                if(isup==='1'){
                    fetch(`/admin/removeItem?itemId=${itemId}`, {
                        method: 'POST',
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 1) {
                                console.log('下架成功');
                                if(selectedStatus==='已上架'){
                                    row.remove();
                                }
                                button.innerHTML = "上架";
                                const pElement = row.querySelector('.isup'); // 这里使用了类名 '.isup'，确保选择器能准确匹配目标元素
// 检查是否成功找到 <p> 元素
                                if (pElement) {
                                    console.log('5555');
                                    // 更新 <p> 元素的文本内容
                                    const newResult = '否'; // 用你想要的新值替换这里的 '新的值'
                                    pElement.innerText = newResult;
                                }

                                console.log('new isup= '+isup);
                            } else {
                                alert('上架失败: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('请求发送失败:', error);
                        });
                }else{
                    fetch(`/admin/rebackItem?itemId=${itemId}`, {
                        method: 'POST',
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 1) {
                                console.log('上架成功');
                                if(selectedStatus==='已下架'){
                                    row.remove();
                                }
                                button.innerHTML = "下架";
                                const pElement = row.querySelector('.isup'); // 这里使用了类名 '.isup'，确保选择器能准确匹配目标元素
// 检查是否成功找到 <p> 元素
                                if (pElement) {
                                    // 更新 <p> 元素的文本内容
                                    const newResult = '是'; // 用你想要的新值替换这里的 '新的值'
                                    pElement.innerText = newResult;
                                }
                            } else {
                                alert('下架失败: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('请求发送失败:', error);
                        });
                }

            }

            function editItem(button){
                var row=button.parentNode.parentNode;  //获取当前行
                var inputFields = row.querySelectorAll('input[type="text"]');
                var saveButton = row.querySelector('#saveItem');
                inputFields.forEach(function(input) {
                    input.removeAttribute("readonly");
                    input.style.border = "1px solid #ccc"; // 可以添加边框样式来提示用户
                });
                button.style.display = "none"; // 隐藏当前行的编辑按钮
                saveButton.style.display='inline-block';
            }

            function saveItem(button){
                var row = button.parentNode.parentNode;
                var price = row.querySelector('.itemPrice').value;
                var qty = row.querySelector('.itemQty').value;
                var id = row.querySelector('td:nth-child(1)').innerText;
                var sale = row.querySelector('td:nth-child(4)').innerText.trim() === '已上架' ? '1' : '0';
                var attr = row.querySelector('.itemAttr').value;
                var editButton=row.querySelector('#editItem');
                var inputFields = row.querySelectorAll('input[type="text"]');
                var data={
                    itemid:id,
                    listprice:price,
                    qty:qty,
                    isup:sale,
                    attr1:attr,
                };
                console.log(data);
                console.log(JSON.stringify(data));
                const url = `/admin/itemsEditor?listprice=${data.listprice}&attr1=${data.attr1}&qty=${data.qty}&isup=${data.isup}&itemid=${data.itemid}`;
                fetch(url,{
                    method:'POST',
                }).then(response => {
                    if (response.ok) {
                        // 请求成功处理逻辑
                        console.log("保存成功");
                        console.log("编辑按钮："+editButton)
                        editButton.style.display='inline-block';
                        button.style.display='none';
                        inputFields.forEach(function (input){
                            input.setAttribute("readonly", "true");
                            input.style.border="none";
                        });
                    } else {
                        // 请求失败处理逻辑
                        console.log("保存失败");
                        alert('商品'+id+'保存失败');
                    }
                })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            }

            //商品排序
            function itemsort(url){
                console.log(url);
                fetch(url,{
                    method:'GET'
                })
                    .then(response => {
                        // console.log(response);
                        if (!response.ok) {
                            throw new Error('Network response was not ok.');
                        }
                        return response.json(); // 解析JSON格式的响应数据
                        // if(url==='/admin/itemOrderBySales'||url==='/admin/itemOrderByPrice'){
                        //     return response.json(); // 解析JSON格式的响应数据
                        // }
                        if(url==='/admin/items'){
                            console.log('全部状态');
                        }
                    })
                    .then(data => {
                        // 处理返回的数据
                        // if (url === '/admin/itemOrderBySales' || url === '/admin/itemOrderByPrice') {
                            tbody.innerHTML = '';
                            var newitems = data.data;
                            console.log('排序');
                            console.log(data.data);
                            updateTbody(newitems);
                       // }
                    })
                    .catch(error => {
                        console.error('请求发生错误', error);
                    });

            }

            //根据状态筛选
            function selectByStatus(button){
                 selectedStatus=button.textContent;
                var url;
                const tbody=document.getElementById('itemTabBody');
                if(selectedStatus==='已上架'){
                    url='itemOrderByIsupTrue';
                }else if(selectedStatus==='已下架'){
                    url='/admin/itemOrderByIsupFalse';
                }else if(selectedStatus==='全部状态'){
                    url='/admin/items';
                }
                    fetch(url)
                        .then(response=>{
                            if(!response.ok){
                                throw new Error('itemOrderByIsupTrue response was not ok ');
                            }
                            // if(url==='/admin/itemOrderByIsupFalse'||url==='itemOrderByIsupTrue'){
                                return response.json();
                            // }
                            // if(url==='/admin/items'){
                            //     window.location.href = url;
                            // }
                        })
                        .then(data=>{
                            // if(url==='/admin/itemOrderByIsupFalse'||url==='itemOrderByIsupTrue'){
                                console.log(data);
                                var newItems=data.data;
                                updateTbody(newItems);
                            // }
                        })
                        .catch(error=>{
                            console.error('请求发生错误',error);
                        })
            }
            function searchItem(){
                console.log('search');
                var keywords=document.getElementById('keyword').value;
                console.log(keywords);
                var url='/admin/getItemListByKeyForJS?keyword='+keywords;
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok.');
                        }
                            return response.json(); // 解析JSON格式的响应数据
                    })
                    .then(data => {
                        // 处理返回的数据
                        console.log(data.data);
                            tbody.innerHTML = '';
                            var newitems = data.data;
                            updateTbody(newitems);
                    })
                    .catch(error => {
                        console.error('请求发生错误', error);
                    });
            }

            function updateTbody(newitems){
                let buttonText= '上架';
                let isupText= '否';
                console.log('update');
                tbody.innerHTML='';
                for (let [key, value] of Object.entries(newitems)) {
                    // console.log("Key:", key);
                    // console.log("Value:", value);
                    const dataString = key;
// 正则表达式匹配 itemid
                    const itemIdMatch = dataString.match(/itemid=([^\s,]+)/);
                    const itemId = itemIdMatch ? itemIdMatch[1] : null;

                    const viewMatch = dataString.match(/views=([^)\s,]+)/);
                    const view = viewMatch ? viewMatch[1] : null;

                    // 正则表达式匹配 listprice
                    const listPriceMatch = dataString.match(/listprice=([^\s,]+)/);
                    const listPrice = listPriceMatch ? listPriceMatch[1] : null;
                    // 正则表达式匹配 categoryid
                    const categoryIdMatch = dataString.match(/catid=([^\s,]+)/);
                    const categoryId = categoryIdMatch ? categoryIdMatch[1] : null;
// 正则表达式匹配 productid
                    const productIdMatch = dataString.match(/productid=([^\s,]+)/);
                    const productId = productIdMatch ? productIdMatch[1] : null;
// 正则表达式匹配 qty
                    const qtyMatch = dataString.match(/qty=([^\s,]+)/);
                    const qty = qtyMatch ? qtyMatch[1] : null;
// 正则表达式匹配 attr1
                    const attr1Match = dataString.match(/attr1=([^\s,]+)/);
                    const attr1 = attr1Match ? attr1Match[1] : null;
// 正则表达式匹配 isup

                    const isupMatch = dataString.match(/isup=(false|true)/);
                    const isupValue = isupMatch ? isupMatch[1] : ''; // 获取捕获组中的第一个值
                    if(isupValue==='false'){
                         buttonText= '上架';
                         isupText= '否';
                    }else{
                         buttonText='下架';
                         isupText='是';
                    }

                    // console.log('buttonText='+buttonText);
                    var newRow = document.createElement('tr');
                    newRow.innerHTML=`
                <td name="itemid" >${itemId}</td>
                <td ><input type="text" name="price" class="itemPrice"></td>
              <td name="category">${categoryId}</td>
                <td name="product" >${productId}</td>
                <td> <input type="text" name="qty" class="itemQty" readonly></td>
                <td name="sales">${value}</td>
                <td>
                    <p class="isup" >
                       ${isupText}
                    </p>
                </td>
                <td name="attr"><input type="text" name="attr" class="itemAttr" readonly></td>
                <td name="views">${view}</td>
                <td>
                    <button class="edit Button" style="display: inline-block;" onclick="editItem(this)" id="editItem">编辑</button>
                    <button class="save Button" style="display: none;" onclick="saveItem(this)" id="saveItem">保存</button>
                     <button class="sell-btn Button" style="display: inline-block;" onclick="onShelf(this)">${buttonText}</button>
                     <button class="delete Button" style="display: inline-block;" onclick="deleteItem(this)" id="deleteItem">删除</button>
                </td>
                    `;
                    var itemPriceInput = newRow.querySelector('.itemPrice');
                    var itemQty=newRow.querySelector('.itemQty');
                    var itemAttr=newRow.querySelector('.itemAttr');
                    itemPriceInput.value = listPrice;
                    itemQty.value=qty;
                    itemAttr.value=attr1;
                    tbody.appendChild(newRow);
                }
            }

            function deleteItem(button){
                var row=button.parentNode.parentNode;
                var id = row.querySelector('td:nth-child(1)').innerText;
                var result = confirm("Are you sure you want to delete the item "+id+"?");
                const url='/admin/deleteItemById?itemId='+id;
                console.log('res'+result);
                if (result){
                    fetch(url,{
                        method:'GET'
                    }).then(response=>response.json())
                        .then(data=>{
                            console.log(111)
                            console.log(data);

                            if(data.status===1){
                                alert('删除成功:');
                                row.remove();
                            }else{
                                alert('删除失败');
                            }

                        }).catch(error=>{
                        console.error('Error:', error);
                    })
                }

            }
</script>
    </div>
</div>
</body>
</html>